package com.chukun.netty.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
 * @author chukun
 * nio 字符集测试
 */
public class NIOCharSetOperator {

    public static void main(String[] args) throws IOException {

        //获取文件
        RandomAccessFile inputRandomAccessFile = new RandomAccessFile("nio_input_charset.txt","r");
        RandomAccessFile outPutRandomAccessFile = new RandomAccessFile("nio_output_charset.txt","rw");

        //获取传输通道
        FileChannel inputChannel = inputRandomAccessFile.getChannel();
        FileChannel outputChannel = outPutRandomAccessFile.getChannel();

        long fileLength = new File("nio_input_charset.txt").length();
        //内存映射文件
        MappedByteBuffer mappedByteBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);
        //获得编解码器
        Charset charset = Charset.forName("utf-8");
        CharsetDecoder utf8Decoder = charset.newDecoder();
        CharsetEncoder utf8Encoder = charset.newEncoder();
        //解码
        CharBuffer charBuffer = utf8Decoder.decode(mappedByteBuffer);
        //编码
        ByteBuffer encoderBuffer = utf8Encoder.encode(charBuffer);
        //写入文件
        outputChannel.write(encoderBuffer);

        //关闭流
        inputRandomAccessFile.close();
        outPutRandomAccessFile.close();
    }
}
